const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    starScore: cc.Label = undefined
    @property([cc.Prefab])
    monsters: cc.Prefab[] = []
    @property(cc.Node)
    startbtn: cc.Node = undefined
    @property(cc.Node)
    moreGame: cc.Node = undefined
    @property(cc.Node)
    shop: cc.Node = undefined
    @property(cc.Node)
    tip: cc.Node = undefined
    @property(cc.Node)
    mask: cc.Node = undefined

    private monster: cc.Node = undefined

    onLoad() {
        this.initScene()
        this.loadMonster()
        this.addEventListen()

    }

    // 添加点击事件
    private addEventListen() {
        this.startbtn.on('touchstart', this.startEvent, this)
        this.moreGame.on('touchstart', this.moreGameEvent, this)
        this.shop.on('touchstart', this.shopEvent, this)
    }

    // 销毁时移除点击事件
    onDestroy(){
        this.startbtn.off('touchstart', this.startEvent, this)
        this.moreGame.off('touchstart', this.moreGameEvent, this)
        this.shop.off('touchstart', this.shopEvent, this)
    }

    // 开始事件
    private startEvent() {
        this.monster.runAction(cc.sequence(cc.moveTo(0.3, this.monster.x, -cc.winSize.height / 2 + this.monster.height / 2), cc.callFunc(() => { cc.director.loadScene('game') })))
    }

    // 更多游戏
    private moreGameEvent() {
        this.mask.active = true
        this.tip.active = true
        this.tip.opacity = 255
        this.mask.zIndex = this.tip.zIndex = 1
        this.tip.setPosition(0, 200)
        this.tip.runAction(cc.sequence(cc.spawn(cc.moveTo(1, 0, 0), cc.fadeOut(1.5)), cc.callFunc(() => {
            this.mask.active = false
            this.tip.active = false
        })))
    }

    // 跳转商店
    private shopEvent() {
        cc.director.loadScene('shop')
    }

    // 初始化场景
    private initScene() {
        let num = cc.sys.localStorage.getItem('star')
        if (num) {
            this.starScore.string = 'x ' + num + ''
        } else {
            this.starScore.string = 'x ' + 0 + ''
        }
    }

    // 加载怪物
    private loadMonster() {
        let node: cc.Node = undefined
        let monster = cc.sys.localStorage.getItem('monster')
        if (monster) {
            node = cc.instantiate(this.monsters[+monster])
        } else {
            node = cc.instantiate(this.monsters[0])
            cc.sys.localStorage.setItem('monster', 0)

        }
        node.parent = this.node
        node.x = -cc.winSize.width / 4
        node.y = -cc.winSize.height / 2 + node.height
        this.monster = node
    }


    // update (dt) {}
}
